﻿package net.wangit.adm.admin;

import net.wangit.context.ActionContext;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.support.action.TransactionAction;
import net.wangit.user.admin.AdminCache;
import net.wangit.util.Checker;

public class AdminAuthAction extends TransactionAction {

	private static final String SQL_CLEAR_ORGANIZATION = "delete from AADMINORG where adminid=?";
	private static final String SQL_CLEAR_GROUP = "delete from AADMINGROUP where adminid=?";
	private static final String SQL_CLEAR_ROLE = "delete from AADMINROLE where adminid=?";

	public AdminAuthAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String aid = ac.getRequestParameter("admin.authorization.adminid");
		if (Checker.isEmpty(aid))
			return;
		db.execute("delete from AADMINORG where adminid=?", aid, 2);
		db.execute("delete from AADMINGROUP where adminid=?", aid, 2);
		db.execute("delete from AADMINROLE where adminid=?", aid, 2);
		String checks[] = ac.getRequestParameters("a.organizations");
		if (!Checker.isEmpty(checks)) {
			Table table = new Table("adm", "AADMINORG");
			for (int i = 0; i < checks.length; i++) {
				ColumnRow row = table.addInsertRow();
				row.set("adminid", aid);
				row.set("orgid", checks[i]);
			}

			db.save(table);
		}
		checks = ac.getRequestParameters("a.groups");
		if (!Checker.isEmpty(checks)) {
			Table table = new Table("adm", "AADMINGROUP");
			for (int i = 0; i < checks.length; i++) {
				ColumnRow row = table.addInsertRow();
				row.set("adminid", aid);
				row.set("groupid", checks[i]);
			}

			db.save(table);
		}
		checks = ac.getRequestParameters("a.roles");
		if (!Checker.isEmpty(checks)) {
			Table table = new Table("adm", "AADMINROLE");
			for (int i = 0; i < checks.length; i++) {
				ColumnRow row = table.addInsertRow();
				row.set("adminid", aid);
				row.set("roleid", checks[i]);
			}

			db.save(table);
		}
		AdminCache.clearAll();
	}
}
